﻿using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace AyuBookmark.Common.Models
{
    /// <summary>
    /// 系统配置项实体类，用于存储用户偏好设置和系统参数
    /// </summary>
    [Table("config")]
    public class ConfigItem
    {
        /// <summary>
        /// 配置键名（主键）
        /// </summary>
        [Key]
        [Column("key")]
        [StringLength(50)]
        [Required(ErrorMessage = "配置键名不能为空")]
        public string Key { get; set; }

        /// <summary>
        /// 配置值（JSON格式存储复杂对象）
        /// </summary>
        [Column("value")]
        [Required(ErrorMessage = "配置值不能为空")]
        public string Value { get; set; }

        /// <summary>
        /// 配置项描述说明
        /// </summary>
        [Column("description")]
        [StringLength(200)]
        public string Description { get; set; }

        /// <summary>
        /// 配置分组（用于界面分类展示）
        /// </summary>
        [Column("category")]
        [StringLength(30)]
        public string Category { get; set; } = "General";

        /// <summary>
        /// 最后更新时间
        /// </summary>
        [Column("last_updated")]
        [DatabaseGenerated(DatabaseGeneratedOption.Computed)]
        public DateTime LastUpdated { get; set; } = DateTime.Now;

        /// <summary>
        /// 是否为敏感配置（决定是否加密存储）
        /// </summary>
        [Column("is_sensitive")]
        public bool IsSensitive { get; set; }

        /// <summary>
        /// 配置项版本号（用于兼容性处理）
        /// </summary>
        [Column("version")]
        public int Version { get; set; } = 1;

        /// <summary>
        /// 将JSON值转换为指定类型
        /// </summary>
        /// <typeparam name="T">目标类型</typeparam>
        /// <returns>反序列化后的对象</returns>
        public T GetValue<T>()
        {
            try
            {
                return System.Text.Json.JsonSerializer.Deserialize<T>(Value);
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException($"Failed to deserialize config value for key '{Key}'", ex);
            }
        }

        /// <summary>
        /// 设置配置值（自动序列化为JSON）
        /// </summary>
        /// <typeparam name="T">值类型</typeparam>
        /// <param name="value">要设置的值</param>
        public void SetValue<T>(T value)
        {
            Value = System.Text.Json.JsonSerializer.Serialize(value);
            LastUpdated = DateTime.Now;
        }

        /// <summary>
        /// 验证配置项有效性
        /// </summary>
        /// <returns>验证结果</returns>
        public bool Validate()
        {
            return !string.IsNullOrWhiteSpace(Key) &&
                   !string.IsNullOrWhiteSpace(Value);
        }

        /// <summary>
        /// 重写ToString方法，返回有意义的配置信息
        /// </summary>
        public override string ToString()
        {
            return $"[{Category}] {Key} = {Value}";
        }
    }

    /// <summary>
    /// 预定义配置键名
    /// </summary>
    public static class ConfigKeys
    {
        public const string StayDuration = "StayDuration";
        public const string PrivacyAccepted = "PrivacyAccepted";
        public const string ThemeColor = "UI.ThemeColor";
        public const string BackupPath = "Storage.BackupPath";
    }

    /// <summary>
    /// 配置项默认值提供器
    /// </summary>
    public static class ConfigDefaults
    {
        public static ConfigItem CreateDefault(string key)
        {
            return key switch
            {
                ConfigKeys.StayDuration => new ConfigItem
                {
                    Key = key,
                    Value = "3",
                    Description = "自动保存的最小停留时间(分钟)"
                },
                ConfigKeys.PrivacyAccepted => new ConfigItem
                {
                    Key = key,
                    Value = "false",
                    IsSensitive = true,
                    Description = "用户是否接受隐私协议"
                },
                _ => new ConfigItem
                {
                    Key = key,
                    Value = string.Empty,
                    Description = "Custom configuration"
                }
            };
        }
    }


}